package com.shengruan.servlet;

import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.shengruan.admin.vo.ProductClass;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import com.shengruan.admin.jdbc.ArticleJdbc;
import com.shengruan.admin.jdbc.ProductClassJdbc;
import com.shengruan.admin.jdbc.ProductJdbc;
import com.shengruan.admin.jdbc.SliderLogoJdbc;
import com.shengruan.admin.jdbc.UserJdbc;
import com.shengruan.admin.vo.User;
import com.shengruan.common.Constants;
import com.shengruan.index.action.AuctionUtil;
import com.shengruan.user.action.AutoAuctionThread;
import com.shengruan.user.action.AutoAuctionUtil;
import com.shengruan.user.action.AutoThreadUtil;
import com.shengruan.user.jdbc.AutoAuctionJdbc;
import com.shengruan.user.vo.AutoAuction;

public class InitSystemServlet extends HttpServlet {

    protected static Logger logger = Logger.getLogger(InitSystemServlet.class);
    /**
     *
     */
    protected static Log log = LogFactory.getLog(InitSystemServlet.class);
    private static final long serialVersionUID = 1L;

    public InitSystemServlet() {
        super();
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    }

    public void init() throws ServletException{

        String appPath = this.getServletContext().getRealPath("/");
        Constants.APP_PATH = appPath;

        /***配置Log4J***/
        String file = getInitParameter("Log4j-init-file");
        if(file != null) {
            /**
             *读取配置文件的方法
             *BasicConfigurator.configure (); 自动快速地使用缺省Log4j环境。
             *PropertyConfigurator.configure ( String configFilename) ;读取使用Java
             *的特性文件编写的配置文件。
             *DOMConfigurator.configure ( String filename ) ;读取XML形式的配置文件。
             */
            PropertyConfigurator.configure(appPath+file);
        }

        /***权限初始化*****/
        // Popedom.initPopURLList();

        //初始化首页公告
        ArticleJdbc articleJdbc = new ArticleJdbc();
        Constants.articleList = articleJdbc.findAll();

        /** 首页滑动Logo初始化 */
        //SliderLogoJdbc sliderLogoJdbc = new SliderLogoJdbc();
        //Constants.sliderLogoList = sliderLogoJdbc.findAll(Constants.STATUS_ACTIVE);

        /**
         * 获得商品分类
         */
        ProductClassJdbc productClassJdbc = new ProductClassJdbc();
        Constants.productClassList = productClassJdbc.getList();
        this.getServletContext().setAttribute(Constants.PRODUCT_CLASS_LIST,productClassJdbc.getList());
        
        /***
         * 初始化竞拍商品
         */
        ProductJdbc productJdbc = new ProductJdbc();
        //productJdbc.intiMapFromDatabase();
        for (ProductClass productClass : Constants.productClassList)
            Constants.PRODUCT_MENU_LIST.put(productClass.getId().toString(),productJdbc.getList(productClass.getId().toString(),null,0));
        this.getServletContext().setAttribute(Constants.PRODUCT_MENU_MAP,Constants.PRODUCT_MENU_LIST);

        /***
         * 定时监测商品状态
         */
        Timer timer = new Timer();
        timer.schedule(new AuctionUtil(),0,1000);


        /***
         * 定期检查商品
         */
        /*Timer timer1 = new Timer();
        timer1.schedule(new CheckProduct(),0,1000*60*60);*/
        /***
         * 恢复用户自动竞拍线程
         */


        /*UserJdbc userJdbc = new UserJdbc();
        AutoAuctionJdbc autoAuctionJdbc = new AutoAuctionJdbc();
        List<User> userList = userJdbc.getAutoBidUserList();
        AutoAuctionThread aat = new AutoAuctionThread();
        Constants.autoAuctionThread = aat;
        for(int i=0;i<userList.size();i++)
        {
            User user = (User)userList.get(i);
            int userId = user.getId();
            List<AutoAuction> aList = autoAuctionJdbc.getList(userId, 1);
            if(aList.size()>0)
            {
                for(int k=0;k<aList.size();k++)
                {
                    AutoAuction autoAuction = (AutoAuction)aList.get(k);
                    AutoAuctionUtil.add(userId+"||"+autoAuction.getProductId(), autoAuction);
                }


                Thread autoTread = new Thread(aat,userId+"");
                autoTread.start();
                AutoThreadUtil.add(userId, autoTread);
            }
            else
            {
                userJdbc.setAutoAuctionState(userId, 0);
            }

        }*/


        try {
            PropertiesConfiguration config = new PropertiesConfiguration("auction.properties");
            Constants.USER_INVITEMAXBIDDING = config.getInt("user.InviteMaxBidding");
            Constants.PRODUCT_DISABLE_DAYS = config.getInt("product.disable.days");
        } catch (ConfigurationException e) {
            e.printStackTrace();
            logger.error("读取classpath下auction.properties文件发生异常，请检查CLASSPATH和文件名是否存在！");
        }


    }
    public static Date getDateType(String time)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try
        {
            return sdf.parse(time);
        }
        catch(Exception ex)
        {
            return new Date();
        }
    }
    public static String getLDate(long time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(new Date(time));
    }
}